# python 3.6.8 
import logging
from urllib.parse import unquote

logging.basicConfig(filename = 'log.log', level = logging.DEBUG, format = ' %(asctime)s - %(levelname)s - %(message)s')
#logging.disable(logging.CRITICAL)

def is_oct(n):
    return True if n.isdigit() and '8' not in n and '9' not in n else False

def restore(cha):
    result = ''
    for j in cha.split('%'):
        if '' == j:
             continue
        logging.debug(f'j: {j}')
        result += '\\' + str(oct(eval('0x' + j))[2:])
    return result

def oct_decode(s):
    words = s.split('\\')
    result = ''
    cha = ''
    tmp_i = ''
    pre = False
    logging.debug(f'words: {words}')
    for i in words:
        if is_oct(i):
            cha += '%' + str(hex(eval('0o' + i)))[2:]
            pre = True
            logging.debug(f'独立的3个数字时: i: {i}, cha: {cha}, pre: {pre}')
        else:
            if len(i) > 3:
                tmp_i = i[:3]
                logging.debug(f'长度大于3时: tmp_i: {tmp_i}')
                if is_oct(tmp_i):
                    cha += '%' + str(hex(eval('0o' + tmp_i)))[2:]
                    pre = True
                    tmp_i = i[3:]
                    logging.debug(f'前3个是八进制数，存入 cha: {cha}, tmp_i: {tmp_i}')
                else:
                    logging.debug(f'前3个不是八进制数: tmp_i: {tmp_i}')
                    tmp_i = '\\' + i
                    pre = False
            else:
                logging.debug(f'长度小于3时: tmp_i: {tmp_i}')
                tmp_i = '\\' + i
                pre = False
            if not pre and len(cha) > 0:
                logging.debug(f'如果当前 i 不是八进制数，就还原内容: cha: {cha}')
                result += restore(cha)
                cha = ''
                pre = False
        if len(cha) == 9 and pre:
            logging.debug(f'组装汉字: cha: {cha}')
            result += unquote(cha)
            cha = ''
        if not pre and len(cha) > 0:
            # 此处的方法修复不了bug，决定换一种方式（另一个脚本）
            result += restore(cha)
        result += tmp_i
        tmp_i = ''
    return result

if __name__ == '__main__':
    import sys
    sys.path.append('../')
    from utils.File import readFile, writeFile
    cont = readFile('f1.txt')
    cont = oct_decode(cont)
    writeFile('f2.txt', cont)
